package com.socialsoftware.ui.Me;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.socialsoftware.R;
import com.socialsoftware.databinding.FragmentMeBinding;
import com.socialsoftware.ui.settings.SettingsActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MeFragment extends Fragment {
    private FragmentMeBinding binding;
    private MeViewModel meViewModel;
    private Bitmap qrCodeBitmap;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        meViewModel = new ViewModelProvider(this).get(MeViewModel.class);

        binding = FragmentMeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // Set user profile information
        TextView nameTextView = binding.profileName;
        TextView wechatIdTextView = binding.profileAccountId;
        
        // Observe the user data from ViewModel
        meViewModel.getUserName().observe(getViewLifecycleOwner(), nameTextView::setText);
        meViewModel.getWechatId().observe(getViewLifecycleOwner(), wechatIdTextView::setText);

        // Set up QR code button click listener
        ImageButton qrCodeButton = binding.qrCodeButton;
        qrCodeButton.setOnClickListener(v -> showQRCodeDialog());
        
        // Set up click listeners for new sections
        setupFavoritesSection();
        setupMomentsSection();
        setupEmojiSection();
        setupWalletSection();
        setupSettingsSection();

        return root;
    }
    
    private void setupFavoritesSection() {
        View favoritesItem = binding.favoritesItem;
        favoritesItem.setOnClickListener(v -> {
            Toast.makeText(requireContext(), "打开收藏", Toast.LENGTH_SHORT).show();
            // Intent intent = new Intent(requireContext(), FavoritesActivity.class);
            // startActivity(intent);
        });
    }
    
    private void setupMomentsSection() {
        View momentsItem = binding.momentsItem;
        TextView momentsBadge = binding.momentsBadge;
        
        // Observe moments updates from ViewModel
        meViewModel.getNewMomentsCount().observe(getViewLifecycleOwner(), count -> {
            if (count > 0) {
                momentsBadge.setVisibility(View.VISIBLE);
                momentsBadge.setText(count + "条新消息");
            } else {
                momentsBadge.setVisibility(View.GONE);
            }
        });
        
        momentsItem.setOnClickListener(v -> {
            Toast.makeText(requireContext(), "打开朋友圈", Toast.LENGTH_SHORT).show();
            // Intent intent = new Intent(requireContext(), MomentsActivity.class);
            // startActivity(intent);
            
            // Clear the badge after viewing
            meViewModel.clearNewMomentsCount();
        });
    }
    
    private void setupEmojiSection() {
        View emojiItem = binding.emojiItem;
        emojiItem.setOnClickListener(v -> {
            Toast.makeText(requireContext(), "打开表情", Toast.LENGTH_SHORT).show();
            // Intent intent = new Intent(requireContext(), EmojiActivity.class);
            // startActivity(intent);
        });
    }
    
    private void setupWalletSection() {
        View walletItem = binding.walletItem;
        walletItem.setOnClickListener(v -> {
            Toast.makeText(requireContext(), "打开支付", Toast.LENGTH_SHORT).show();
            // Intent intent = new Intent(requireContext(), WalletActivity.class);
            // startActivity(intent);
        });
    }
    
    private void setupSettingsSection() {
        View settingsItem = binding.settingsItem;
        settingsItem.setOnClickListener(v -> {
            Intent intent = new Intent(requireContext(), SettingsActivity.class);
            startActivity(intent);
        });
    }

    private void showQRCodeDialog() {
        Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_qr_code);
        
        ImageView qrCodeImageView = dialog.findViewById(R.id.qr_code_image);
        TextView nameTextView = dialog.findViewById(R.id.qr_name);
        TextView infoTextView = dialog.findViewById(R.id.qr_info);
        
        // Set user name in the dialog
        meViewModel.getUserName().observe(getViewLifecycleOwner(), name -> {
            nameTextView.setText(name);
        });
        
        // Generate QR code with username for friend requests
        try {
            String username = meViewModel.getUsername().getValue();
            if (username != null) {
                // Format the QR code content as JSON with type identifier
                String qrContent = "{\"type\":\"friend_request\",\"username\":\"" + username + "\"}";
                qrCodeBitmap = generateQRCode(qrContent);
                qrCodeImageView.setImageBitmap(qrCodeBitmap);
                
                // Display additional info
                infoTextView.setText("扫一扫上面的二维码，加我为好友");
            }
        } catch (WriterException e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "生成二维码失败", Toast.LENGTH_SHORT).show();
        }
        
        // Set close button click listener
        dialog.findViewById(R.id.btn_close).setOnClickListener(v -> dialog.dismiss());
        
        // Set save button click listener
        Button saveButton = dialog.findViewById(R.id.btn_save);
        saveButton.setOnClickListener(v -> saveQRCodeToGallery());
        
        // Set share button click listener
        Button shareButton = dialog.findViewById(R.id.btn_share);
        shareButton.setOnClickListener(v -> shareQRCode());
        
        dialog.show();
    }
    
    private void saveQRCodeToGallery() {
        if (qrCodeBitmap == null) {
            Toast.makeText(requireContext(), "二维码不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // Create a file name with timestamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String fileName = "QRCode_" + timeStamp + ".jpg";
        
        boolean success = false;
        
        // For Android 10 (API 29) and above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = requireContext().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            
            Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            
            if (imageUri != null) {
                try (OutputStream outputStream = resolver.openOutputStream(imageUri)) {
                    success = qrCodeBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            // For older Android versions
            File imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File image = new File(imagesDir, fileName);
            
            try (FileOutputStream outputStream = new FileOutputStream(image)) {
                success = qrCodeBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            // Notify gallery about the new image
            if (success) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(image);
                mediaScanIntent.setData(contentUri);
                requireContext().sendBroadcast(mediaScanIntent);
            }
        }
        
        if (success) {
            Toast.makeText(requireContext(), "二维码已保存到相册", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(requireContext(), "保存二维码失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void shareQRCode() {
        if (qrCodeBitmap == null) {
            Toast.makeText(requireContext(), "二维码不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // Create a temporary file to share
        try {
            File cachePath = new File(requireContext().getCacheDir(), "images");
            cachePath.mkdirs();
            File imageFile = new File(cachePath, "shared_qr_code.jpg");
            
            FileOutputStream stream = new FileOutputStream(imageFile);
            qrCodeBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.close();
            
            // Get the content URI for the file using FileProvider
            Uri contentUri = FileProvider.getUriForFile(requireContext(), 
                    requireContext().getPackageName() + ".fileprovider", imageFile);
            
            // Create share intent
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/jpeg");
            shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            // Add text message with the share
            String username = meViewModel.getUsername().getValue();
            if (username != null) {
                shareIntent.putExtra(Intent.EXTRA_TEXT, "扫描二维码添加我为好友: " + username);
            }
            
            // Start the share activity
            startActivity(Intent.createChooser(shareIntent, "分享二维码"));
            
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "分享二维码失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private Bitmap generateQRCode(String content) throws WriterException {
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(
                    content,
                    BarcodeFormat.QR_CODE,
                    500, 500, null
            );
        } catch (IllegalArgumentException e) {
            return null;
        }
        
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
            }
        }
        
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        
        return bitmap;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}